package com.app.twth.ui.finalprocess.submit;


import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.app.MyApplication;
import com.app.twth.base.BaseActivity;
import com.app.twth.bean.PrintSku;
import com.app.twth.databinding.ActivityFinalprocessSubmitBinding;
import com.app.twth.databinding.DialogPrinterConnectHintBinding;
import com.app.twth.ui.finalprocess.FinalProcessQr;
import com.app.twth.ui.finalprocess.FinalProcessViewModel;
import com.app.twth.ui.printer.DeviceConnFactoryManager;
import com.app.twth.ui.printer.PrinterActivity;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

/**
 * @describe :
 */
public class FinalProcessSubmitActivity extends BaseActivity<ActivityFinalprocessSubmitBinding, FinalProcessViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private FinalProcessQr finalProcessQr;

    @Override
    protected void initListener() {
        viewModel.finalProcessLiveData.observe(this, data -> {
            Intent intent = new Intent();
            intent.putExtra("FinalProcessReturn", data);
            setResult(RESULT_OK, intent);
            finish();
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "FinalProcess(Submit)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext(getString(R.string.submit));
        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        finalProcessQr = (FinalProcessQr) bundle.getSerializable("FinalProcessQr");

        binding.tvBatchNo.setText(finalProcessQr.getBatchNo());
        binding.tvOriginalLpn.setText(finalProcessQr.getOldIbLpn());
        binding.tvTrk.setText(finalProcessQr.getTrackingCode());
        binding.tvQty.setText(finalProcessQr.getQty() + "");
        determineType();

        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);
        binding.tvCode.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeSku.setOnFocusChangeListener(onFocusChangeListener);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                binding.tvCode.requestFocus();
                setScan();
                break;
            case R.id.iv_scan_barcode:
                binding.tvCodeSku.requestFocus();
                setScan();
                break;
            case R.id.tv_print2:
                if (MyApplication.printerService.mIsConnected) {
                    if (!MyApplication.printerService.isConnected()) {//判断打印机状态
                        showPrinterConnectDialog();
                        return;
                    }
                    String status = MyApplication.printerService.printHint;
                    if (!Utils.isEmpty(status)) {//判断打印机状态
                        ToastUtil.showToast(status);
                        return;
                    }
                } else if (DeviceConnFactoryManager.getDeviceConnFactoryManager() == null ||
                        !DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState()) {
                    ToastUtil.showToast(getString(R.string.str_cann_printer));
                    return;
                }
//                PrintSku printLpn = new PrintSku();
//                printLpn.setType(3);
//                viewModel.printSku(printLpn);
                viewModel.returnFinalProcessPrintLpn(finalProcessQr);
                break;
            case R.id.tv_print:
                //处理类型 1:指定销毁/2:上架/3:返还客户/4:重新拍照,可用值:1,2,3,4
                PrintSku printSku = new PrintSku();
                if (finalProcessQr.getType() == 1) {//指定销毁
                    printSku.setSku(finalProcessQr.getOpenLassSku());
                    printSku.setType(2);
                }
                if (finalProcessQr.getType() == 2) {//上架
                    printSku.setSku(finalProcessQr.getNewSku());
                    printSku.setType(1);
                }
                if (MyApplication.printerService.mIsConnected) {
                    if (!MyApplication.printerService.isConnected()) {//判断打印机状态
                        showPrinterConnectDialog();
                        return;
                    }
                    String status = MyApplication.printerService.printHint;
                    if (!Utils.isEmpty(status)) {//判断打印机状态
                        ToastUtil.showToast(status);
                        return;
                    }
                } else if (DeviceConnFactoryManager.getDeviceConnFactoryManager() == null ||
                        !DeviceConnFactoryManager.getDeviceConnFactoryManager().getConnState()) {
                    ToastUtil.showToast(getString(R.string.str_cann_printer));
                    return;
                }
                viewModel.printSku(printSku);
                break;
            case R.id.tv_reset:
                binding.tvCode.requestFocus();
                binding.tvCode.setText("");
                binding.tvCodeSku.setText("");
                bottomLayoutBinding.tvHint.setText("");
                break;
            case R.id.tv_next:
                if (System.currentTimeMillis() - timeMillis < spaceTime) {//两秒内触发一次
                    return;
                }
                timeMillis = System.currentTimeMillis();
                setSubmit();
                break;
        }
    }

    private void determineType() {
        if (finalProcessQr.getAccountId() != 0) {
            binding.tvAccountIdHint.setVisibility(View.VISIBLE);
            binding.tvAccountId.setVisibility(View.VISIBLE);
            binding.tvAccountId.setText(finalProcessQr.getAccountId() + "");
        }
        if (finalProcessQr.getType() == 1) {//销毁
            binding.layoutSku.setVisibility(View.VISIBLE);
            if (!Utils.isEmpty(finalProcessQr.getSku())) {
                binding.tvSku.setText(finalProcessQr.getSku() + "");
                binding.tvSku.setVisibility(View.VISIBLE);
                binding.tvSkuHint.setVisibility(View.VISIBLE);
            }
            if (!Utils.isEmpty(finalProcessQr.getOpenLassSku())) {
                binding.tvNewSku.setText(finalProcessQr.getOpenLassSku() + "");
            }
            binding.tvCode.setHint("Please input new inbound lpn");
            binding.layoutNewSku.setVisibility(View.VISIBLE);
            return;
        }
        if (finalProcessQr.getType() == 2) {//上架
            binding.layoutSku.setVisibility(View.VISIBLE);
            if (!Utils.isEmpty(finalProcessQr.getSku())) {
                binding.tvSku.setText(finalProcessQr.getSku() + "");
                binding.tvSku.setVisibility(View.VISIBLE);
                binding.tvSkuHint.setVisibility(View.VISIBLE);
            }
            if (!Utils.isEmpty(finalProcessQr.getNewSku())) {
                binding.tvNewSku.setText(finalProcessQr.getNewSku() + "");
                binding.layoutNewSku.setVisibility(View.VISIBLE);
            }
            binding.tvCode.setHint("Please input new inbound lpn");
            return;
        }
        if (finalProcessQr.getType() == 3) {//返还客户
            binding.tvPrint2.setVisibility(View.VISIBLE);
            binding.tvCode.setHint("Please input new outbound lpn");
            return;
        }
    }

    View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                switch (v.getId()) {
                    case R.id.tv_code:
                        type = 0;
                        break;
                    case R.id.tv_code_sku:
                        type = 1;
                        break;
                }
            } else {
                type = 0;
            }
        }
    };

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                EditTextUtil.hideInput(mContext);

                if (Utils.isEmpty(barcodeStr)) {
                    return false;
                }
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        switch (type) {
            case 0:
                binding.tvCode.setText(barcodeStr);
                binding.tvCodeSku.requestFocus();
                break;
            case 1:
                binding.tvCodeSku.setText(barcodeStr);
                break;
        }
    }

    private void setSubmit() {
        String lpn = binding.tvCode.getText().toString();
        String code_sku = binding.tvCodeSku.getText().toString();

        finalProcessQr.setNewIbLpn(lpn);
        switch (finalProcessQr.getType()) {
            case 1://销毁
                if (Utils.isEmpty(lpn)) {
                    ToastUtil.showToast("Please input new inbound lpn");
                    return;
                }
                finalProcessQr.setNewIbLpn(lpn);

                finalProcessQr.setOpenLassSku(code_sku);
                if (Utils.isEmpty(code_sku)) {
                    ToastUtil.showToast("Please input sku/barcode");
                    return;
                }
                break;
            case 2://上架
                if (Utils.isEmpty(lpn)) {
                    ToastUtil.showToast("Please input new inbound lpn");
                    return;
                }
                finalProcessQr.setNewIbLpn(lpn);

                finalProcessQr.setNewSku(code_sku);
                if (Utils.isEmpty(code_sku)) {
                    ToastUtil.showToast("Please input sku/barcode");
                    return;
                }
                break;
            case 3://返还客户
                if (Utils.isEmpty(lpn)) {
                    ToastUtil.showToast("Please input new outbound lpn");
                    return;
                }
                finalProcessQr.setNewIbLpn(lpn);
                break;
        }

        viewModel.returnFinalProcessSubmit(finalProcessQr);
    }

    private AlertDialog dialogPrinterConnect;

    private void showPrinterConnectDialog() {
        dialogPrinterConnect = MyDialogUtil.getDialog(this, initPrinterConnectDialogView(), Gravity.CENTER);
        dialogPrinterConnect.setCanceledOnTouchOutside(false);
        dialogPrinterConnect.show();
    }

    private View initPrinterConnectDialogView() {
        DialogPrinterConnectHintBinding dialogBinding = DialogPrinterConnectHintBinding.inflate(LayoutInflater.from(this));
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogPrinterConnect != null) {
                dialogPrinterConnect.dismiss();
            }
        });
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            if (dialogPrinterConnect != null) {
                dialogPrinterConnect.dismiss();
            }
            AppRouter.showFragmentActivity(this, PrinterActivity.class);
        });
        return dialogBinding.getRoot();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
